<template>
  <div class="bgff p20" v-loading="loading">
    <el-form :inline="true" :model="formInline" class="demo-form-inline mb20">
      <el-form-item label="网关名">
        <el-select v-model="gatewayId" placeholder="请选择">
          <el-option v-for="item in gatewaylist" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择日期">
        <el-date-picker
          v-model="time"
          type="month"
          placeholder="选择日期"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="serch">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-download" @click="outPdf">导出PDF</el-button>
      </el-form-item>
    </el-form>
    <div class="con" id="week-report">
      <div class="bor">
        <div class="p1">{{gatewayNameFn(gatewayId)}} {{new Date(timeText).format('yyyy-MM')}} 月报</div>
        <table
          cellpadding="0"
          cellspacing="1"
          width="100%"
          class="eqmt-con bb"
          style="background-color: white;"
        >
          <tr class="tr1">
            <td>监控区域</td>
            <td>设备状态</td>
            <td>报警次数</td>
          </tr>
          <tr v-for="item in tableData" :key="item.id">
            <td>{{item.name}}</td>
            <td>{{item.alarm>0?'报警':'正常'}}</td>
            <td>{{item.alarm}}</td>
          </tr>
        </table>
        <p
          class="fz12 p10"
        >报警次数总计{{all.total()}}次。剩余电流报警{{all.di}}次，线缆电流报警{{all.a}}次，线缆温度报警为{{all.t}}次，线缆电压报警为{{all.v}}次。详情请登录安心电管家管理平台。</p>
      </div>
      <div class="clear mt20">
        <div class="fl" id="line1" style="width:30%;height:300px;"></div>
        <div class="fr" id="line2" style="width:70%;height:300px;"></div>
      </div>
      <div class="clear">
        <div class="fl" id="line3" style="width:70%;height:300px;"></div>
        <div class="fr" id="line4" style="width:30%;height:300px;"></div>
      </div>
      <div class="clear">
        <div class="fl" id="line5" style="width:70%;height:300px;"></div>
        <div class="fr" id="line6" style="width:30%;height:300px;"></div>
      </div>
      <div class="mt20">
        <h3 class="titles mb10">危害分类</h3>
        <div v-html="article"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { _chartReportMonth, _gatewaysAllGet, _articleShow } from "@/http/ajax";
import htmlToPdf from "@/utils/htmlToPdf";
import conf from "@/http/uploadconfig";
export default {
  data() {
    let inittime = new Date(
      new Date().getTime() - 30 * 24 * 3600 * 1000
    ).format("yyyy-MM");
    return {
      pickerOptions: {
        disabledDate(time) {
          let curDate = new Date().getTime();
          let three = 30 * 24 * 3600 * 1000;
          let threeMonths = curDate - three;
          return time.getTime() > threeMonths;
        }
      },
      time: inittime,
      timeText: "",
      gatewayId: " ",
      gatewaylist: [{}],
      loading: true,
      formInline: {
        input: ""
      },
      tableData: [],
      all: {
        a: 0,
        di: 0,
        t: 0,
        v: 0,
        total: () => {
          return this.all.a + this.all.di + this.all.t + this.all.v;
        },
        eq_total: 0,
        eq_alarm: 0,
        eq_offline: 0,
        eq_online: 0
      },
      article: ""
    };
  },
  created() {
    this.getGatewaysAll();
  },
  mounted() {},
  methods: {
    // 画图
    drawLine(da) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById(da.dom));
      let option = {
        title: {
          text: da.title,
          // subtext: "纯属虚构",
          top: "4%",
          x: "left"
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        grid: {
          left: "3%",
          right: "3%",
          bottom: "2%"
        },
        series: [
          {
            name: da.series_text,
            type: "pie",
            radius: "55%",
            center: ["50%", "60%"],
            data: da.data,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              },
              normal: {
                color: function(params) {
                  //自定义颜色
                  var colorList = ["#26ca91", "#fd7262", "#999999", "#338ff6"];
                  return colorList[params.dataIndex];
                }
              }
            }
          }
        ]
      };
      myChart.setOption(option);
    },
    // 报警次数趋势变化
    drawpie(data) {
      let date1 = [],
        s_a_di = [],
        s_a_i = [],
        s_a_t = [],
        s_a_v = [];
      data.forEach(el => {
        date1.push(new Date(el.create_at).format("dd日"));
        s_a_di.push(el.s_a_di);
        s_a_i.push(el.s_a_i);
        s_a_t.push(el.s_a_t);
        s_a_v.push(el.s_a_v);
      });
      let myChart = this.$echarts.init(document.getElementById(`line2`));
      let option = {
        title: {
          text: "报警次数趋势变化",
          top: "4%"
        },
        tooltip: {
          trigger: "axis"
        },
        legend: {
          bottom: "1%",
          data: ["线缆电流", "剩余电流", "线缆电压", "线缆温度"]
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "10%",
          containLabel: true
        },
        // toolbox: {
        //   feature: {
        //     saveAsImage: {}
        //   }
        // },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: date1
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            name: "线缆电流",
            type: "line",
            stack: "总量1",
            data: s_a_i
          },
          {
            name: "剩余电流",
            type: "line",
            stack: "总量2",
            data: s_a_di
          },
          {
            name: "线缆电压",
            type: "line",
            stack: "总量3",
            data: s_a_v
          },
          {
            name: "线缆温度",
            type: "line",
            stack: "总量4",
            data: s_a_t
          }
        ]
      };
      myChart.setOption(option);
    },
    // 画图
    drawzhu(da) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById(da.dom));
      let option = {
        title: {
          text: da.title,
          // subtext: "纯属虚构",
          top: "4%",
          x: "left"
        },
        color: ["#3398DB"],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: [
          {
            type: "category",
            data: da.category,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: "value"
          }
        ],
        series: [
          {
            name: da.series_text,
            type: "bar",
            barWidth: "100%",
            data: da.data,
            itemStyle: {
              //上方显示数值
              normal: {
                label: {
                  show: true, //开启显示
                  position: "top" //在上方显示
                }
              }
            }
          }
        ]
      };
      myChart.setOption(option);
    },
    gatewayNameFn(v) {
      let text = "";
      this.gatewaylist.forEach(el => {
        if (v == el.id) {
          text = el.name;
        }
      });
      return text;
    },
    // pdf 导出
    outPdf() {
      htmlToPdf.downloadPDF(
        document.querySelector("#week-report"),
        this.gatewayNameFn(this.gatewayId) +"（" +this.timeText + "）月报"
      );
    },
    // 搜索
    serch() {
      this.getData();
    },

    getData() {
      var firstDate = new Date(this.time);
      firstDate.setDate(1); //第一天
      var endDate = new Date(firstDate);
      endDate.setMonth(firstDate.getMonth() + 1);
      endDate.setDate(0);
      let data = {
        endTime: new Date(endDate).format("yyyy-MM-dd"),
        gatewayId: this.gatewayId,
        startTime: new Date(firstDate).format("yyyy-MM-dd")
      };
      this.all.di = 0;
      this.all.a = 0;
      this.all.t = 0;
      this.all.v = 0;

      this.loading = true;
      this.timeText = new Date(this.time).format("yyyy-MM");
      this.tableData = [];
      _chartReportMonth(
        data,
        res => {
          // this.tableData = res.equipments;
          let equipments = res.equipments;
          equipments.forEach(el => {
            let obj = {
              name: el.name,
              alarm: 0
            };
            for (var key in el.data) {
              obj.alarm += el.data[key];
            }
            this.tableData.push(obj);
          });
          setTimeout(() => {
            // 画图
            this.doRes(res);
          }, 100);
          this.all.eq_total = res.equipments.length;
          this.all.eq_alarm = res.alarm_numbers;
          this.all.eq_offline = res.offline_numbers;
          this.all.eq_online =
            this.all.eq_total - this.all.eq_alarm - this.all.eq_offline;
          this.loading = false;
          this.getArticle();
        },
        err => {}
      );
    },
    // 获取所有网关
    getGatewaysAll() {
      let user = JSON.parse(sessionStorage.user);
      let data = {
        deptId: user.deptId || user.dept.id || "",
        level: sessionStorage.level
      };
      _gatewaysAllGet(
        data,
        res => {
          this.gatewaylist = res;
          if (this.gatewaylist.length) {
            this.gatewayId = this.gatewaylist[0].id;
          } else {
            this.gatewayId = '';
          }
          this.getData();
        },
        err => {}
      );
    },
    doRes(res) {
      this.all.di = 0;
      this.all.a = 0;
      this.all.t = 0;
      this.all.v = 0;
      let days = res.data_total;
      let eqmtlist = res.equipments;
      let s_a_di = 0, // 剩余电流
        s_a_i = 0, // 电流
        s_a_t = 0, // 温度
        s_a_v = 0, // 电压
        thisMounthData = [];
      eqmtlist.forEach(el => {
        this.all.di = s_a_di += el.data.s_a_di;
        this.all.a = s_a_i += el.data.s_a_i;
        this.all.t = s_a_t += el.data.s_a_t;
        this.all.v = s_a_v += el.data.s_a_v;
      });
      this.drawLine({
        title: "报警类型次数统计",
        series_text: "报警次数统计",
        dom: "line1",
        data: [
          { value: s_a_i, name: "线缆电流" },
          { value: s_a_di, name: "剩余电流" },
          { value: s_a_v, name: "线缆电压" },
          { value: s_a_t, name: "线缆温度" }
        ]
      });
      // // 每天数据
      let s_t_20_30 = 0,
        s_t_30_40 = 0,
        s_list_150 = 0,
        s_list_300 = 0,
        s_list_500 = 0,
        s_list_500_ = 0;
      days.forEach((it, i) => {
        s_t_20_30 += it.s_t_20_30 || 0;
        s_t_30_40 += it.s_t_30_40 || 0;
        s_list_150 += it.s_list_150 || 0;
        s_list_300 += it.s_list_300 || 0;
        s_list_500 += it.s_list_500 || 0;
        s_list_500_ += it.s_list_500_ || 0;
      });
      this.drawpie(days);
      this.drawzhu({
        series_text: "数量",
        dom: "line3",
        title: "线缆温度分布情况",
        data: [s_t_20_30, s_t_30_40],
        category: ["20-30℃", "30-40℃"]
      });
      this.drawLine({
        title: "线缆温度统计",
        series_text: "线缆温度统计",
        dom: "line4",
        data: [
          { value: s_t_20_30, name: "20-30℃" },
          { value: s_t_30_40, name: "30-40℃" }
        ]
      });
      this.drawzhu({
        series_text: "数量",
        dom: "line5",
        title: "线缆剩余电流分布情况",
        data: [s_list_150, s_list_300, s_list_500, s_list_500_],
        category: ["0-150mA", "150-300mA", "300-500mA", "500mA以上"]
      });
      this.drawLine({
        title: "剩余电流统计",
        series_text: "剩余电流统计",
        dom: "line6",
        data: [
          { value: s_list_150, name: "0-150mA" },
          { value: s_list_300, name: "150-300mA" },
          { value: s_list_500, name: "300-500mA" },
          { value: s_list_500_, name: "500mA以上" }
        ]
      });
    },
    // 没有数据
    noDdata(id, type) {
      let type_modul = {
        a_h: "高峰用电电流",
        list_a_h: "线缆最高温度",
        u_h: "高峰剩余电流",
        t_h: "监控区域最高温度"
      };
      $(`#line_${type}_${id}`).css({ height: "220px" })
        .html(`<div class="bold pl30 pt10">
            ${type_modul[type]}
          </div>
          <div class="tx-c">
            <img alt="" src="${conf.nodata}"> 
          </div>`);
    },
    // 获取知识库
    getArticle() {
      _articleShow(
        5,
        res => {
          this.article = res.content;
        },
        err => {}
      );
    }
  }
};
</script>

<style lang="scss" scoped>
.con {
  min-width: 860px;
  .bor {
    border: 1px solid #ccc;
    border-radius: 5px;
  }
  .tz-bg {
    background: #a0d468;
    color: #fff;
  }
  .titles {
    height: 37px;
    line-height: 37px;
    font-size: 14px;
    border: 1px solid #d2d2d2;
    border-left: 3px solid #509de2;
    padding-left: 10px;
    padding-right: 26px;
    background: #fff;
    color: #666;
    display: inline-block;
  }
  .p1 {
    background: #509de3;
    border-radius: 3px;
    height: 50px;
    line-height: 50px;
    color: #fff;
    font-size: 14px;
    padding-left: 20px;
    text-align: left;
  }
  .eqmt-con {
    background: #f0f0f0;
    text-align: left;
    border-collapse: inherit;
    border-spacing: 2px;
    tr td {
      background: #f6f6f6;
      padding: 10px 20px;
    }
    .tr1 td {
      background: #f7f7f7;
      border-top: 1px solid #bfbfbf;
      border-bottom: 3px solid #a0d468;
    }
    .img-tips {
      width: 9px;
      height: 9px;
      vertical-align: middle;
    }
  }
}
</style>
